import {bus} from '@beshell/events-ts/bus'
import { conn } from '@beshell/conn-ts/Connection'
import {AppModel} from '../AppModel'
import { PartSlaver } from './PartBase'
import { Cable } from '../conn/Cable'
import { I2C } from '../conn/I2C'
import config from './config/BeColorDetector.json'

export class BeColorDetector extends PartSlaver {

    constructor(_model: AppModel){
        super(_model, config)

        this.handleWatchRemoteData = (device:string, data: any)=>{
            if(device!=this.instanceName) {
                return
            }
            this.r = data[0]
            this.g = data[1]
            this.b = data[2]
        }
        bus.on('remote.sensor.data', this.handleWatchRemoteData)
    }

    destroy() {
        super.destroy()

        if(this.handleWatchRemoteData) {
            bus.off('remote.sensor.data', this.handleWatchRemoteData)
            this.handleWatchRemoteData = null
        }
    }

    public c: number = 0
    public r: number = 0
    public g: number = 0
    public b: number = 0

    private handleWatchRemoteData: any = null
    
    // serial(): Cable | undefined {
    //     return this.studs[1][0].bus?.findCable() || this.studs[1][1].bus?.findCable()
    // }

    public begin() {
        // let serial = this.serial()
        // if(!serial) {
        //     return false
        // }
        // if(!(serial instanceof I2C) || !serial.isValid()){
        //     return false
        // }

        return true
    }

    public async remoteRead() {
        if(!conn.isConnected)
            return
        let color = await conn.console.call(`resolve(${this.remoteVar()}.read())`)
        if(!color)
            return
        this.r = color.r[0]
        this.g = color.r[1]
        this.b = color.r[2]
        return color
    }

    public remoteWatch() {
        if(!conn.isConnected)
            return
        conn.console.run(`if(${this.remoteVar()}.__handle==undefined){
            ${this.remoteVar()}.__handle = ${this.remoteVar()}.watch(function(r,g,b){
                console.log("run<<EmitEvent('sensor', \\\"${this.instanceName}\\\", ["+r+","+g+","+b+"])")
            })
        }
        ${this.remoteVar()}.start()`)
    }

    public remoteUnwatch() {
        if(!conn.isConnected)
            return
        conn.console.run(`${this.remoteVar()}.stop()`)
    }
    
    public generateSetupCode(indent=0){
        return `${"\t".repeat(indent)}${this.remoteVar()} = new be.driver.BeColorDetector()`
    }

    public generateBeginCode(indent=0){
        return ""
    }
}